package com.example.demo.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.example.demo.common.CustomException;
import com.example.demo.common.R;
import com.example.demo.common.UserContext;
import com.example.demo.entity.AddressBook;
import com.example.demo.entity.Orders;
import com.example.demo.service.AddressBookService;
import com.example.demo.service.OrdersService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.List;

/**
 * date 2022年07月24日 16:06
 */
@Slf4j
@RestController
@RequestMapping("/addressBook")
public class AddressBookController {
    @Autowired
    private AddressBookService addressBookService;
    @Autowired
    private OrdersService ordersService;
    /**
     * 新增
     */
    @PostMapping
    public R<AddressBook> save(@RequestBody AddressBook addressBook) {
        addressBook.setUserId(UserContext.getUserId());
        log.info("addressBook:{}", addressBook);
        addressBookService.save(addressBook);
        return R.success(addressBook);
    }
    /**
     * 设置默认地址
     */
    @PutMapping("default")
    public R<AddressBook> setDefault(@RequestBody AddressBook addressBook) {
        log.info("addressBook:{}", addressBook);
        UpdateWrapper<AddressBook> wrapper = new UpdateWrapper<>();
        wrapper.lambda().
                eq(AddressBook::getUserId,UserContext.getUserId());
        wrapper.lambda().
                set(AddressBook::getUserId,0);
        addressBookService.update(addressBook,wrapper);
        addressBook.setIsDefault(1);
        addressBookService.updateById(addressBook);
        return R.success(addressBook);
    }
    @GetMapping("/list")
    public R<List<AddressBook>> list(AddressBook addressBook) {
        addressBook.setUserId(UserContext.getUserId());
        log.info("addressBook:{}", addressBook);
        //条件构造器
        LambdaQueryWrapper<AddressBook> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(null != addressBook.getUserId(), AddressBook::getUserId, addressBook.getUserId());
        queryWrapper.orderByDesc(AddressBook::getUpdateTime);

        //SQL:select * from address_book where user_id = ? order by update_time desc
        return R.success(addressBookService.list(queryWrapper));
    }

    /**
     * 根据id查询地址
     */
    @GetMapping("/{id}")
    public R get(@PathVariable Long id) {
        AddressBook addressBook = addressBookService.getById(id);
        if (addressBook != null) {
            return R.success(addressBook);
        } else {
            return R.error("没有找到该对象");
        }
    }
    /**
     * 查询默认地址
     */
    @GetMapping("default")
    public R<AddressBook> getDefault() {
        LambdaQueryWrapper<AddressBook> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(AddressBook::getUserId,UserContext.getUserId());
        wrapper.eq(AddressBook::getIsDefault,1);
        AddressBook addressBook = addressBookService.getOne(wrapper);
        if(addressBook ==null){
            return R.error("没有找到该对象");
        }else {
            return R.success(addressBook);
        }
    }
    @PutMapping
    public R<String> updateAddress(@RequestBody AddressBook addressBook) {
        // 判断是否有订单
        Long id = addressBook.getId();
        existOrder(id);
        // 查询出地址 根据id修改
        addressBook.setUpdateTime(new Date());
        addressBookService.updateById(addressBook);
        return R.success("地址修改成功");
    }

    /**
     * 判断地址是否正在使用中
     * @param id
     */
    private void existOrder(Long id) {
        LambdaQueryWrapper<Orders> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Orders::getAddressBookId, id);
        wrapper.ne(Orders::getStatus, 4);
        int count = ordersService.count(wrapper);
        if (count > 0) {
            throw new CustomException("您有订单还未完成 暂时不能修改地址！！");
        }
    }

    @DeleteMapping
    public R<String> delete(@RequestParam Long ids) {
        this.existOrder(ids);
        addressBookService.removeById(ids);
        return R.success("删除成功");
    }
}
